package com.fling.abcde.adapter;

import androidx.recyclerview.widget.RecyclerView;

import android.view.ViewGroup;

import java.lang.ref.WeakReference;

public class CommonRecyclerAdapter extends RecyclerView.Adapter {
    private CommonCallBack mCallback;

    public interface CommonCallBack {
        default int getItemViewType(int position) {
            return 0;
        }

        int getItemCount();

        RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType);

        void onBindViewHolder(RecyclerView.ViewHolder holder, int adapterPosition);
    }

    /**
     * 当需要根据itemViewType来动态创建多个ViewHolder时，必须调用此方法，
     * 并手动覆写 {@link CommonCallBack#getItemViewType}
     * 和{@link CommonCallBack#onCreateViewHolder}方法。
     *
     * @param callback
     */
    public CommonRecyclerAdapter(CommonCallBack callback) {
        //弱引用 免泄露
        mCallback = new WeakReference<>(callback).get();
    }

    @Override
    public int getItemViewType(int position) {

        return mCallback == null ? 0 : mCallback.getItemViewType(position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        return mCallback == null ? null : mCallback.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (mCallback != null) {
            mCallback.onBindViewHolder(holder, holder.getAdapterPosition());
        }
    }

    @Override
    public int getItemCount() {

        return mCallback == null ? 0 : mCallback.getItemCount();
    }
}